package com.example.day14_service;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Intent;
import android.content.Context;
import android.os.Build;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;


public class MyIntentService extends IntentService {

    public MyIntentService() {
        super("MyIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d("sss", "onHandleIntent: 执行耗时任务，一般用来下载音频");
        String path = intent.getStringExtra("path");
        String file = intent.getStringExtra("file");

        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(path).openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            if(connection.getResponseCode()==200){
                InputStream stream = connection.getInputStream();
                FileOutputStream outputStream = new FileOutputStream(new File(file));
                //进度条通知 需要两个值--max  progress
                int max = connection.getContentLength();
                int progress = 0;
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = stream.read(bytes))!=-1){
                    progress+=len;//更新进度条
                    //发送通知
                    sendNoti(max,progress);
                    outputStream.write(bytes,0,len);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    private void sendNoti(int max, int progress) {
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification.Builder builder = new Notification.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("正在下载")
                .setProgress(max, progress, false)
                .setAutoCancel(true);
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
            manager.createNotificationChannel(new NotificationChannel("id","name",NotificationManager.IMPORTANCE_DEFAULT));
            builder.setChannelId("id");
        }
        //startForeground(1,builder.build());//开前台服务，会根据service销毁自动销毁
        //发送通知
        manager.notify(1,builder.build());
        if(max==progress){
            manager.cancel(1);
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("sss", "onCreate: 被创建");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("sss", "onDestroy: 被销毁");
    }
}